<?php
declare (strict_types = 1);

namespace app\middleware;

use app\api\model\AuthRule;
use app\api\model\Users;
use think\facade\Request;

class Authenticate
{
    /**
     * @param $request
     * @param \Closure $next
     * @User: 刘海龙
     * @Date: 2021/2/25
     * @Time: 15:05
     * @return mixed|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 处理请求
     */
    public function handle($request, \Closure $next)
    {
        $header = Request::instance()->header();
        if (!array_key_exists('authorization', $header)) {
            return json([
                'code' => 1002,
                'data' => ['message' => 'Token不存在,拒绝访问']
            ]);
        }
        if (empty($header['authorization'])) {
            return json([
                'code' => 1002,
                'data' => ['message' => 'Token为空,拒绝访问']
            ]);
        }
        $jwt = json_decode(verifyJwt($header['authorization']), true);
        if ($jwt['code'] == 1001) {
            if (!array_key_exists('source', $header)) {
                $user = Users::find($jwt['data']['uid']);
                // 检查用户权限
                $role_ids = array_column($user->roles()->select()->toArray(),
                    'rules');//获取该用户所属角色rules

                if (in_array('*', $role_ids)) {
                    $request->uid = $jwt['data']['uid'];
                    return $next($request);
                }

                $url = [];
                $res = AuthRule::where('id', 'in', implode(',', $role_ids))
                    ->select()->toArray();

                foreach ($res as $key => $v) {
                    $url[] = $v['name'];
                }
                $get_rule = $request->rule()->getRule(); //获取当前路由
                $get_rule = explode('/<',$get_rule);
                if (in_array(array_shift($get_rule), $url)) {
                    $request->uid = $jwt['data']['uid'];
                    return $next($request);
                }
                return json([
                    'code' => 403,
                    'data' => ['message' => '无权限, 请联系管理员申请']
                ]);
            }else{
                return $next($request);
            }
        }
        return json($jwt);
    }
}
